package com.tianjin.weight.utils;

import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.springframework.stereotype.Component;

import javax.xml.bind.DatatypeConverter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;


@Component
public class ImgTransUtils {

    public static String ConvertSvg2Png(String dataSvgUri) throws IOException, TranscoderException {
        InputStream in = new ByteArrayInputStream(
                DatatypeConverter.parseBase64Binary(dataSvgUri.substring(dataSvgUri.indexOf(",") + 1))
        );
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Transcoder transcoder = new PNGTranscoder();
        try{
            TranscoderInput input = new TranscoderInput(in);
            try{
                TranscoderOutput output = new TranscoderOutput(out);
                transcoder.transcode(input,output);
            }
            finally {
                out.close();
            }
        }
        finally {
            in.close();
        }

        String finalPngStr = DatatypeConverter.printBase64Binary(out.toByteArray());
        return "data:image/png;base64,"+finalPngStr;
    }

}
